package com.unit.util;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;

public class TimeUtil {
	/**
	 * 匹配时间格式：yyyy-MM-dd HH:mm:ss ; yyyy/MM/dd HH:mm:ss
	 * 增加了针对于csv默认打开无秒数
	 * @param value
	 * @return
	 */
	public static boolean isTimeString(String value){
		String ymd = "(19|20)\\d{2}(-|/)((0?[1-9])|(1[012]))(-|/)((0?[1-9])|([12]\\d)|(3[01]))";
		String hms = "((0?\\d)|([1-5]\\d)):((0?\\d)|([1-5]\\d))(:((0?\\d)|([1-5]\\d)))?";
		String pattern = ymd + " " + hms;
		Pattern r = Pattern.compile(pattern);	 
	    return r.matcher(value).matches();
	}
	
	/**
	 * @param dateStr 日期格式的字符串
	 * @return true : dataStr格式为 yyyy/MM/dd, yyyy-MM-dd
	 */
	public static boolean isDateString(String dateStr) {
		String pattern = "(19|20)\\d{2}(-|/)((0?[1-9])|(1[012]))(-|/)((0?[1-9])|([12]\\d)|(3[01]))";	
	    Pattern r = Pattern.compile(pattern);	 
	    return r.matcher(dateStr).matches();  	      
	}	
	
	public static LocalDate convertLocalDate(String date) throws Exception {
		if(isDateString(date)) {
			if(StringUtils.isNumeric(date)) {
				return LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyyMMdd"));
			}else {
				String[] ymd = date.contains("-")?date.split("-"):date.split("/");
				return LocalDate.of(Integer.valueOf(ymd[0]), Integer.valueOf(ymd[1]), Integer.valueOf(ymd[2]));
			}
		}else {			
			throw new Exception("日期格式不正确:"+date);
		}
	}
	
	public static LocalDateTime convertLocalDateTime(String datetime) throws Exception {
		if(isTimeString(datetime)) {
			if(StringUtils.isNumeric(datetime)) {
				return LocalDateTime.parse(datetime, DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
			}else {
				String date = StringUtils.split(datetime, " ")[0];
				String[] ymd = date.contains("-")?date.split("-"):date.split("/");
				LocalDate localDate = LocalDate.of(Integer.valueOf(ymd[0]), Integer.valueOf(ymd[1]), Integer.valueOf(ymd[2]));
				String time = StringUtils.split(datetime, " ")[1];
				if(time.split(":").length == 2) {
					time = time+":00";
				}
				LocalTime localTime = LocalTime.parse(time);
				return LocalDateTime.of(localDate, localTime);
			}
		}else {			
			throw new Exception("日期格式不正确:"+datetime);
		}
	}
	
}
